const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../module/resModel')
const blogRouter = async (req, res) => {
  //根据不通的路由匹配对应的controller层
  const path = req.path
  const method = req.method
  res.setHeader('Content-Type', 'application/json')

  if (path === '/api/blog/list' && method === 'GET') {
    const author = req.query.author || ''
    const keyword = req.query.keyword || ''
    let data = await getList(author, keyword)
    return new SuccessModel(data)
  } else if (path === '/api/blog/new' && method === 'POST') {
    const bodyData = req.body
    if (bodyData.title) {
      let data = await newBlog(bodyData)
      if (data) return new SuccessModel(data, '新建博客成功')
      return new ErrorModel('新建博客失败')
    } else return new ErrorModel('新建博客失败,没有传入数据')
  } else if (path === '/api/blog/detail' && method === 'GET') {
    const id = req.query.id
    if (id) {
      let res = await getDetail(id)
      return new SuccessModel(res)
    } else return new ErrorModel('获取博客详情失败,没有传入id')
  } else if (path === '/api/blog/update' && method === 'POST') {
    const id = req.query.id
    const data = req.body
    if (id && data.title) {
      let res = await updateBlog(id, data)
      if (res) {
        return new SuccessModel(res)
      } else return new ErrorModel('更新博客失败')
    }
    return new ErrorModel('更新博客失败,没有传入id')
  } else if (path === '/api/blog/delete' && method === 'POST') {
    const id = req.query.id
    if (id) {
      let res = await delBlog(id)
      if (res) {
        return new SuccessModel(res, '删除成功')
      } else return new ErrorModel('删除博客失败')
    }
    return new ErrorModel('删除博客失败,没有传入id')
  } else return false
}

module.exports = blogRouter
